<template>
    <u-tabbar
        v-model="current"
        v-bind="tabbarStyle"
        :list="tabbarList"
        @change="handleChange"
        :hide-tab-bar="true"
    ></u-tabbar>
</template>

<script lang="ts" setup>
import { useAppStore } from '@/stores/app'
import { useUserStore } from '@/stores/user'
import { navigateTo } from '@/utils/util'
import { computed, ref, onMounted, watch } from 'vue'
import { onShow } from '@dcloudio/uni-app'

const current = ref(0)

// 延迟初始化 store，避免在 Pinia 未完全初始化时调用
let appStore: ReturnType<typeof useAppStore> | null = null
let userStore: ReturnType<typeof useUserStore> | null = null

// 更新当前选中项
const updateCurrent = () => {
    if (!appStore) return
    
    const pages = getCurrentPages()
    if (pages.length === 0) return
    
    const currentPage = pages[pages.length - 1]
    const currentRoute = '/' + currentPage.route
    
    // 获取 tabBar 配置
    const tabbarConfig = appStore.getTabbarConfig || []
    const index = tabbarConfig.findIndex((item: any) => {
        try {
            const link = JSON.parse(item.link)
            return link.path === currentRoute
        } catch (e) {
            return false
        }
    })
    
    if (index >= 0) {
        current.value = index
    }
}

// 在 onMounted 中初始化 store，确保 Pinia 已完全初始化
onMounted(() => {
    appStore = useAppStore()
    userStore = useUserStore()
    updateCurrent()
})

// 监听页面显示，更新当前选中项
onShow(() => {
    updateCurrent()
})

// 监听 tabbarList 变化，更新选中项
watch(() => appStore?.getTabbarConfig, () => {
    updateCurrent()
}, { immediate: true })

const tabbarList = computed(() => {
    if (!appStore) return []
    return appStore.getTabbarConfig.map((item: any) => {
        const link = JSON.parse(item.link)
        return {
            iconPath: item.unselected,
            selectedIconPath: item.selected,
            text: item.name,
            link,
            count: link.path == '/pages/shop_cart/shop_cart' ? (userStore?.shopCartCount || 0) : 0,
            pagePath: link.path
        }
    })
})

const showTabbar = computed(() => {
    const currentPages = getCurrentPages()
    const currentPage = currentPages[currentPages.length - 1]
    const current = tabbarList.value.findIndex((item: any) => {
        return item.pagePath === '/' + currentPage.route
    })
    return current >= 0
})
const nativeTabList = [
    '/pages/index/index',
    '/pages/category/category',
    '/pages/shop_cart/shop_cart',
    '/pages/user/user'
]
const tabbarStyle = computed(() => ({
    activeColor: appStore?.getStyleConfig?.selectedColor || '#000000',
    inactiveColor: appStore?.getStyleConfig?.defaultColor || '#999999'
}))
const handleChange = (index: number) => {
    const selectTab = tabbarList.value[index]
    current.value = index
    if (nativeTabList.includes(selectTab.link.path)) {
        uni.switchTab({
            url: selectTab.link.path
        })
    } else {
        navigateTo(selectTab.link, 'reLaunch')
    }
}
</script>
